<?php

namespace App\Service\Pay;

use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\Pay\RmsPayEnum;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Service\BaseService;
use App\Service\OpenShop\Wap\SignOrderService;
use Illuminate\Http\Request;

class CallbackService extends BaseService
{
    private int    $sysType;
    private int    $operateType;
    private int    $orderId;
    private int    $amount;
    private string $payNo;
    private string $refundNo;
    private int    $refundStatus;
    private string $bizId;

    /**
     * 入口方法
     * @param Request $request
     */
    public function entrance(Request $request)
    {
        $this->sysType      = (int)$request->get('sysType');
        $this->operateType  = (int)$request->get('operateType');
        $this->orderId      = (int)$request->get('orderId');
        $this->amount       = (int)$request->get('amount');
        $this->payNo        = (string)$request->get('payNo');
        $this->refundNo     = (string)$request->get('refundNo');
        $this->refundStatus = (int)$request->get('refundStatus');
        $this->bizId        = (string)$request->get('bizId');

        // TODO 后期用设计模式改
        if ($this->operateType == RmsPayEnum::OPERATE_TYPE_PAY) {
            $this->pay();
            return;
        }

        if ($this->operateType == RmsPayEnum::OPERATE_TYPE_REFUND) {
            $this->refund();
            return;
        }

        throw new CustomHttpResponseException(
            ErrCode::errCodeTrans(ErrCode::CODE_SIGN_ORDER_PAY_CALLBACK_OPERATE)
        );
    }

    /**
     * 支付回调
     */
    private function pay()
    {
        // 将payHistoryId转成orderNo
        $orderNo = (string)OpenShopSignOrderPayHistoryModel::query()
                                                           ->where('id', $this->orderId)
                                                           ->value('orderNo');

        // 处理支付成功
        (new SignOrderService($orderNo, null, false, true))->paySuccess($this->orderId, $this->amount);
    }

    /**
     * 退款回调
     */
    private function refund()
    {
        throw new CustomHttpResponseException(
            ErrCode::errCodeTrans(ErrCode::CODE_SIGN_ORDER_PAY_CALLBACK_OPERATE)
        );
    }
}
